import pytest
import tempfile
import os
import sqlite3
import pandas as pd
from datetime import datetime, timedelta
from decimal import Decimal
import sys
import shutil

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from core.models import Order, Trade
from storage.sqlalchemy_storage import SQLAlchemyStorage
from storage.sqlite3_storage import SQLite3Storage
from adapters.tradingview_adapter import TradingViewAdapter
from core.trade_processor import TradeProcessor


@pytest.fixture
def temp_db_path():
    """创建临时数据库文件路径"""
    with tempfile.NamedTemporaryFile(suffix='.db', delete=False) as f:
        temp_path = f.name
    yield temp_path
    # 清理
    if os.path.exists(temp_path):
        try:
            os.unlink(temp_path)
        except PermissionError:
            # Windows上可能文件还在使用中，忽略错误
            pass


@pytest.fixture
def temp_dir():
    """创建临时目录"""
    temp_dir = tempfile.mkdtemp()
    yield temp_dir
    # 清理
    shutil.rmtree(temp_dir, ignore_errors=True)


@pytest.fixture
def sqlalchemy_storage(temp_db_path):
    """创建SQLAlchemy存储实例"""
    storage = SQLAlchemyStorage(temp_db_path)
    yield storage
    storage.close()


@pytest.fixture
def sqlite3_storage(temp_db_path):
    """创建SQLite3存储实例"""
    storage = SQLite3Storage(temp_db_path)
    yield storage
    storage.close()


@pytest.fixture
def tradingview_adapter():
    """创建TradingView适配器实例"""
    return TradingViewAdapter()


@pytest.fixture
def trade_processor(tradingview_adapter, sqlalchemy_storage):
    """创建交易处理器实例"""
    return TradeProcessor(tradingview_adapter, sqlalchemy_storage)


@pytest.fixture
def sample_orders():
    """创建示例订单数据"""
    orders = []
    
    # 第一个订单
    order1 = Order()
    order1.order_id = "1001"
    order1.symbol = "MESM25"
    order1.side = "buy"
    order1.order_type = "market"
    order1.quantity = float(Decimal("1"))
    order1.filled = float(Decimal("1"))
    order1.quantity_left = float(Decimal("0"))
    order1.limit_price = None
    order1.stop_price = None
    order1.avg_fill_price = float(Decimal("5000.00"))
    order1.status = "filled"
    order1.open_time = datetime(2025, 6, 14, 9, 30, 0)
    order1.close_time = datetime(2025, 6, 14, 9, 30, 5)
    order1.duration = "00:00:05"
    order1.commission = float(Decimal("2.50"))
    order1.expiration = None
    order1.multiplier = float(Decimal("5"))
    orders.append(order1)
    
    # 第二个订单
    order2 = Order()
    order2.order_id = "1002"
    order2.symbol = "MESM25"
    order2.side = "sell"
    order2.order_type = "market"
    order2.quantity = float(Decimal("1"))
    order2.filled = float(Decimal("1"))
    order2.quantity_left = float(Decimal("0"))
    order2.limit_price = None
    order2.stop_price = None
    order2.avg_fill_price = float(Decimal("5010.00"))
    order2.status = "filled"
    order2.open_time = datetime(2025, 6, 14, 10, 0, 0)
    order2.close_time = datetime(2025, 6, 14, 10, 0, 5)
    order2.duration = "00:00:05"
    order2.commission = float(Decimal("2.50"))
    order2.expiration = None
    order2.multiplier = float(Decimal("5"))
    orders.append(order2)
    
    # 第三个订单
    order3 = Order()
    order3.order_id = "1003"
    order3.symbol = "MESM25"
    order3.side = "buy"
    order3.order_type = "limit"
    order3.quantity = float(Decimal("2"))
    order3.filled = float(Decimal("2"))
    order3.quantity_left = float(Decimal("0"))
    order3.limit_price = float(Decimal("5005.00"))
    order3.stop_price = None
    order3.avg_fill_price = float(Decimal("5005.00"))
    order3.status = "filled"
    order3.open_time = datetime(2025, 6, 14, 11, 0, 0)
    order3.close_time = datetime(2025, 6, 14, 11, 0, 10)
    order3.duration = "00:00:10"
    order3.commission = float(Decimal("5.00"))
    order3.expiration = None
    order3.multiplier = float(Decimal("5"))
    orders.append(order3)
    
    # 第四个订单
    order4 = Order()
    order4.order_id = "1004"
    order4.symbol = "MESM25"
    order4.side = "sell"
    order4.order_type = "market"
    order4.quantity = float(Decimal("2"))
    order4.filled = float(Decimal("2"))
    order4.quantity_left = float(Decimal("0"))
    order4.limit_price = None
    order4.stop_price = None
    order4.avg_fill_price = float(Decimal("5015.00"))
    order4.status = "filled"
    order4.open_time = datetime(2025, 6, 14, 12, 0, 0)
    order4.close_time = datetime(2025, 6, 14, 12, 0, 8)
    order4.duration = "00:00:08"
    order4.commission = float(Decimal("5.00"))
    order4.expiration = None
    order4.multiplier = float(Decimal("5"))
    orders.append(order4)
    
    return orders


@pytest.fixture
def sample_trades():
    """创建示例交易数据"""
    trades = []
    
    # 第一个交易
    trade1 = Trade()
    trade1.trade_id = "10011002"
    trade1.symbol = "MESM25"
    trade1.open_datetime = datetime(2025, 6, 14, 9, 30, 5)
    trade1.open_price = 5000.00
    trade1.open_qty = 1
    trade1.close_datetime = datetime(2025, 6, 14, 10, 0, 5)
    trade1.close_price = 5010.00
    trade1.close_qty = 1
    trade1.direction = "Long"
    trade1.open_order_type = "market"
    trade1.trade_type = ""
    trade1.side = None
    trade1.point_profit_per_lot = 10.00
    trade1.total_points = 10.00
    trade1.gross_profit = 50.00
    trade1.net_profit = 45.00
    trade1.commission = 5.00
    trade1.holding_time = "00:30:00"
    trade1.nth_trade = 1
    trade1.session = "RTH"
    trade1.max_floating_profit_points = None
    trade1.max_floating_profit_dollars = None
    trade1.max_floating_loss_points = None
    trade1.max_floating_loss_dollars = None
    trade1.entry_reason = None
    trade1.exit_reason = None
    trade1.stop_loss_price = None
    trade1.stop_loss_reason = None
    trade1.take_profit_price = None
    trade1.take_profit_reason = None
    trades.append(trade1)
    
    # 第二个交易
    trade2 = Trade()
    trade2.trade_id = "10031004"
    trade2.symbol = "MESM25"
    trade2.open_datetime = datetime(2025, 6, 14, 11, 0, 10)
    trade2.open_price = 5005.00
    trade2.open_qty = 2
    trade2.close_datetime = datetime(2025, 6, 14, 12, 0, 8)
    trade2.close_price = 5015.00
    trade2.close_qty = 2
    trade2.direction = "Long"
    trade2.open_order_type = "limit"
    trade2.trade_type = ""
    trade2.side = None
    trade2.point_profit_per_lot = 10.00
    trade2.total_points = 20.00
    trade2.gross_profit = 100.00
    trade2.net_profit = 90.00
    trade2.commission = 10.00
    trade2.holding_time = "00:59:58"
    trade2.nth_trade = 2
    trade2.session = "RTH"
    trade2.max_floating_profit_points = None
    trade2.max_floating_profit_dollars = None
    trade2.max_floating_loss_points = None
    trade2.max_floating_loss_dollars = None
    trade2.entry_reason = None
    trade2.exit_reason = None
    trade2.stop_loss_price = None
    trade2.stop_loss_reason = None
    trade2.take_profit_price = None
    trade2.take_profit_reason = None
    trades.append(trade2)
    
    return trades


@pytest.fixture
def sample_csv_data():
    """创建示例CSV数据"""
    return pd.DataFrame({
        'Order ID': ['1001', '1002', '1003', '1004'],
        'Symbol': ['MESM25', 'MESM25', 'MESM25', 'MESM25'],
        'Side': ['buy', 'sell', 'buy', 'sell'],
        'Type': ['market', 'market', 'limit', 'market'],
        'Quantity': [1, 1, 2, 2],
        'Filled': [1, 1, 2, 2],
        'Quantity Left': [0, 0, 0, 0],
        'Limit': [None, None, 5005.00, None],
        'Stop': [None, None, None, None],
        'Avg Fill Price': [5000.00, 5010.00, 5005.00, 5015.00],
        'Status': ['filled', 'filled', 'filled', 'filled'],
        'Open Time': ['2025/6/14 9:30', '2025/6/14 10:00', '2025/6/14 11:00', '2025/6/14 12:00'],
        'Close Time': ['2025/6/14 9:30', '2025/6/14 10:00', '2025/6/14 11:00', '2025/6/14 12:00'],
        'Duration': ['00:00:05', '00:00:05', '00:00:10', '00:00:08'],
        'Commission Fee': [2.50, 2.50, 5.00, 5.00],
        'Expiration Date': [None, None, None, None]
    })


@pytest.fixture
def sample_csv_file(temp_dir, sample_csv_data):
    """创建示例CSV文件"""
    csv_path = os.path.join(temp_dir, 'test_orders.csv')
    sample_csv_data.to_csv(csv_path, index=False)
    return csv_path


@pytest.fixture
def complex_orders():
    """创建复杂的订单数据用于测试各种场景"""
    orders = []
    base_time = datetime(2025, 6, 14, 9, 0, 0)
    
    # 场景1: 简单的开平仓
    orders.extend([
        Order(order_id="2001", symbol="MESM25", side="buy", order_type="market",
              quantity=Decimal("1"), filled=Decimal("1"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5000.00"), status="filled",
              open_time=base_time, close_time=base_time + timedelta(seconds=5),
              commission=Decimal("2.50"), multiplier=Decimal("5")),
        Order(order_id="2002", symbol="MESM25", side="sell", order_type="market",
              quantity=Decimal("1"), filled=Decimal("1"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5010.00"), status="filled",
              open_time=base_time + timedelta(minutes=30), close_time=base_time + timedelta(minutes=30, seconds=5),
              commission=Decimal("2.50"), multiplier=Decimal("5"))
    ])
    
    # 场景2: 加仓后平仓
    orders.extend([
        Order(order_id="2003", symbol="MESM25", side="buy", order_type="market",
              quantity=Decimal("1"), filled=Decimal("1"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5020.00"), status="filled",
              open_time=base_time + timedelta(hours=1), close_time=base_time + timedelta(hours=1, seconds=5),
              commission=Decimal("2.50"), multiplier=Decimal("5")),
        Order(order_id="2004", symbol="MESM25", side="buy", order_type="market",
              quantity=Decimal("1"), filled=Decimal("1"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5025.00"), status="filled",
              open_time=base_time + timedelta(hours=1, minutes=15), close_time=base_time + timedelta(hours=1, minutes=15, seconds=5),
              commission=Decimal("2.50"), multiplier=Decimal("5")),
        Order(order_id="2005", symbol="MESM25", side="sell", order_type="market",
              quantity=Decimal("2"), filled=Decimal("2"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5030.00"), status="filled",
              open_time=base_time + timedelta(hours=2), close_time=base_time + timedelta(hours=2, seconds=8),
              commission=Decimal("5.00"), multiplier=Decimal("5"))
    ])
    
    # 场景3: 反手交易
    orders.extend([
        Order(order_id="2006", symbol="MESM25", side="buy", order_type="market",
              quantity=Decimal("1"), filled=Decimal("1"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5040.00"), status="filled",
              open_time=base_time + timedelta(hours=3), close_time=base_time + timedelta(hours=3, seconds=5),
              commission=Decimal("2.50"), multiplier=Decimal("5")),
        Order(order_id="2007", symbol="MESM25", side="sell", order_type="market",
              quantity=Decimal("2"), filled=Decimal("2"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5035.00"), status="filled",
              open_time=base_time + timedelta(hours=3, minutes=30), close_time=base_time + timedelta(hours=3, minutes=30, seconds=8),
              commission=Decimal("5.00"), multiplier=Decimal("5")),
        Order(order_id="2008", symbol="MESM25", side="buy", order_type="market",
              quantity=Decimal("1"), filled=Decimal("1"), quantity_left=Decimal("0"),
              avg_fill_price=Decimal("5030.00"), status="filled",
              open_time=base_time + timedelta(hours=4), close_time=base_time + timedelta(hours=4, seconds=5),
              commission=Decimal("2.50"), multiplier=Decimal("5"))
    ])
    
    return orders 